<!-- app录音、保存、播放录音 -->
<template>
	<view>
	<view class="content">
			<image class="logo" src="/static/logo.png"></image>
	</view>

	<view>
		<u-select v-model="show" :list="list" @confirm="confirm"></u-select>
		<u-button @click="show = true">循环周期{{show_value}}秒</u-button>
		<!-- <u-select v-model="show" mode="single-column" :list="list" @confirm="confirm"></u-select> -->
	</view>
	
	<view class="wrap">

		<u-row gutter="16" class="row">
			<u-col span="4">
        		<button @tap="startRecord">开始录音</button>
			</u-col>
			<u-col span="4">
        		<button @tap="endRecord">停止录音</button>
			</u-col>
			<u-col span="4">
        		<button @tap="playVoice">播放录音</button>
			</u-col>
		</u-row>
		<u-row gutter="16" class="row">
			<!-- <u-col span="4">
        		<button @tap="playVoice">播放录音</button>
			</u-col> -->
			<u-col span="4">
				<button @tap="getFile">本地文件</button>
			</u-col>
			<u-col span="8">
				<button @tap="stopMp3">播放音乐停止</button>
			</u-col>
		</u-row>
    </view>
        <!-- <button @tap="startRecord">开始录音</button>
        <button @tap="endRecord">停止录音</button>
        <button @tap="playVoice">播放录音</button>
		<button @tap="getFile">本地文件</button>
		<button @tap="stopMp3">播放音乐停止</button> -->
		<list>
			<cell v-for="(item, index) in fileList" :key="item.createTime">
			<u-row gutter="16" class="row">
				<u-col span="9">
				<button data-src="item.filePath" @tap="openMp3(item.filePath)">{{item.time}}-{{item.size}}</button>
				</u-col>
				<u-col span="3">
				<button data-src="item.filePath" @click="removeMp3(item.filePath)">删除</button>
				</u-col>
			</u-row>
			</cell>
		</list>
		<!-- {{fileList}} -->
	</view>
		


</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();

	
	innerAudioContext.autoplay = true;

	export default {
	    data() {
	        return {
				status: 'loadmore',
				count:0,
	            text: '录音',
	            voicePath: '',
				fileList:[],
				// fileList:[
				// 	{'filePath':11111111,'createTime':1111111111111111}
				// ],
				innerAudioContextObj:{},
				topicData:{},
				timer:'',
				recordEndStatus:true, //录音播放完成
				filePathList:[], //文件列表
				show_value:20, //循环探测音频时间
				show: false, //显示下拉
				list: [
					{
						value: 1,
						label: '周期1s'
					},
					{
						value: 5,
						label: '周期5s'
					},
					{
						value: 10,
						label: '周期10s'
					},
					{
						value: 20,
						label: '周期20s'
					},
					{
						value: 40,
						label: '周期40s'
					},
					{
						value: 60,
						label: '周期1分钟'
					},
				],
				
	        }
	    },
	    onLoad() {
	        let self = this;
	        recorderManager.onStop(function (res) {
	            console.log('recorder stop' + JSON.stringify(res));
	            self.voicePath = res.tempFilePath;
				
				var tempFilePaths = self.voicePath
				uni.saveFile({
				  tempFilePath: tempFilePaths,
				  success: function (res) {
					var savedFilePath = res.savedFilePath;
					// _doc/uniapp_save/16203465225730.mp3 
					console.log('保存路径',savedFilePath)
					self.getFile(); //录制结束回调加载
					
				  }
				});
	        });
			self.getFile();  //页面首次加载
			self.loopFun();


	    },
	    methods: {
			confirm(e) {
				const self = this
				this.show_value = e[0].value

				clearInterval(self.timer)
				console.log(e[0].label,e[0].value,this.timer);
				self.loopFun();
			},
			datetime(date = new Date(), format) {
			            format = format || 'YYYY-MM-DD HH:mm:ss';
			
			            const fn = function (d) {
			                return ('0' + d).slice(-2);
			            };
			
			            const d = new Date(date);
			            const formats = {
			                YYYY: d.getFullYear(),
			                MM: fn(d.getMonth() + 1),
			                DD: fn(d.getDate()),
			                HH: fn(d.getHours()),
			                mm: fn(d.getMinutes()),
			                ss: fn(d.getSeconds())
			            };
			
			            return format.replace(/([a-z])\1+/ig, function (a) {
			                return formats[a] || a;
			            });
			},
			loopFun() {  
				const self = this;
				console.log(Date.now())  
				self.timer = setInterval(() => {  
					this.count += 1;  
					console.log('run tim',this.count,this.recordEndStatus)
					// if(this.count === 5) {  
					// 	clearInterval(this.timer)    
					// 	console.log(Date.now())  
					// }  
					if(this.recordEndStatus){
						this.getTopic();
					}
					
				}, this.show_value*1000); 
				 console.log('show_value',this.show_value*1000)
			},
			postTopic(data) {
				// console.log('run post topic')
				// this.topicData
				return uni.request({
				        url: 'http://www.huaibeishi.net:/api/postTopicJson',
						dataType: 'text',
						data: data,
						method:"POST",
				    })
				    
			},
			getTopic() {
				this.recordEndStatus = false
				// console.log('run get topic')
				uni.request({
				        url: 'http://www.huaibeishi.net/api/readTopicJson'
				    })
				    .then(data => {//data为一个数组，数组第一项为错误信息，第二项为返回数据
				        var [error, res]  = data;
						// console.log('error',error)
				  //       console.log('data',res.data);
						this.topicData = res.data.data
						// console.log('topicData',this.topicData)
						
						if(this.topicData.haogeoyes_topic_20210120083829){
							if(this.topicData.haogeoyes_topic_20210120083829.client_type == 'play_record'){
								this.topicData.haogeoyes_topic_20210120083829.client_type = 'stop_record'
								this.postTopic(this.topicData).then(data => {//data为一个数组，数组第一项为错误信息，第二项为返回数据
									var [error, res]  = data;
									if(!error){
										for(let i in this.fileList){
											// console.log(this.fileList[i].filePath)
											this.filePathList.push(this.fileList[i].filePath)
										}
										// console.log('filePathList',filePathList)
										this.openMp3List(this.filePathList)
									}else{
										this.recordEndStatus = true
									}
								});
							}else{
								this.recordEndStatus = true
							}
						}else{
							this.recordEndStatus = true
						}
						// console.log('topicData',this.topicData)								
				    })
			},
			openMp3List(){
				console.log('start filePathList',this.filePathList)
				let self = this
				
				// filePath = '_doc/uniapp_save/16203465225730.mp3'
				let filePath = self.filePathList[0]
				if(filePath){
					const recorderManager = uni.getRecorderManager();
					const innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.autoplay = true;
					innerAudioContext.src = filePath;
					
					// innerAudioContext.loop = true; // 循环播放
					innerAudioContext.onPlay(() => {
					  // console.log('开始播放');
					});
					innerAudioContext.onError((res) => {
					  // console.log(res.errMsg);
					  // console.log(res.errCode);
					});
					innerAudioContext.onEnded(() => {
					  console.log('播放完成');
					  self.filePathList.splice(0,1);
					  console.log('222')
					  this.openMp3List(self.filePathList);
					});
					
				}else{
					console.log('所有播放结束')
					self.recordEndStatus = true
					// this.loopFun();
					
				}
				
			},
			
			stopMp3(){
				
				console.log('停止播放',innerAudioContext.stop());
			},
	        startRecord() {
	            console.log('开始录音');
	
	            recorderManager.start();
	        },
	        endRecord() {
	            console.log('录音结束');
	            recorderManager.stop();

	        },
	        playVoice() {
	            console.log('播放录音');
	
	            if (this.voicePath) {
	                innerAudioContext.src = this.voicePath;
					// InnerAudioContext.src = '_doc/uniapp_save/16203465225730.mp3';
	                innerAudioContext.play();
	            }
	        },
			getFile(){
				let self = this;
				uni.getSavedFileList({
				  // filePath: 'unifile://somefile', //仅做示例用，非真正的文件路径
				  
				  
				  filePath: '_doc/uniapp_save/',
				  success: function (res) {
				    // console.log(res.fileList);
					for(let i in res.fileList){
						// console.log(formatDate(res.fileList[i]))
						res.fileList[i]['time'] = self.datetime(res.fileList[i].createTime) 
					}
					self.fileList = res.fileList;

				    
				  }
				});
			},
			openMp3(filePath){
				// filePath = '_doc/uniapp_save/16203465225730.mp3'
				
				innerAudioContext.autoplay = true;
				innerAudioContext.src = filePath;
				// innerAudioContext.loop = true; // 循环播放
				innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
				  console.log(res.errMsg);
				  console.log(res.errCode);
				});
				innerAudioContext.onEnded(() => {
				  console.log('播放完成');
				});
				this.innerAudioContextObj = innerAudioContext;
			},
			removeMp3(filePath){
					  let self = this
					  console.log('开始删除文件：',filePath)
				      uni.removeSavedFile({
				        filePath: filePath,
				        complete: function (res) {
				          console.log('删除完成',res);
						  self.getFile();
				        }
				      });
	
			}
	    }
	}
	
</script>

<style>
	.row {
		margin-top:70rpx ;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>